//
//  PrescriptionOrderLogisticsViewModel.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2021/8/18.
//  Copyright © 2021 QDSG. All rights reserved.
//

import UIKit
import HandyJSON

class PrescriptionOrderLogisticsViewModel: NSObject {
    var updateClosure: (() -> ())?
    
    private var items: [PrescriptionOrderLogisticsSectionViewModel] = []
    
    var numberOfSections: Int { items.count }
    
    func numberOfRows(in section: Int) -> Int {
        viewModel(in: section).numberOfRows
    }
    
    func viewModel(in section: Int) -> PrescriptionOrderLogisticsSectionViewModel {
        items[section]
    }
    
    private(set) var logisticsNo: String?
}

extension PrescriptionOrderLogisticsViewModel {
    /// 获取处方订单物流信息
    /// expressNum: 快递单号
    func getLogisticsInfo(expressNum: String) {
        HUDTool.showActivity()
        let target = ApiManager.prescriptionOrderLogisticsInfo(expressNum: expressNum)
        HttpTool.shared.request(target: target) { json, code in
            YSGLog("处方订单物流信息 json: \(json)")
            HUDTool.hideActivity()
            switch code {
            case .failure:
                HUDTool.showError(message: json["message"].description)
            case .success:
                if let models = JSONDeserializer<PrescriptionOrderLogistics>.deserializeModelArrayFrom(json: json["data"].description) as? [PrescriptionOrderLogistics] {
                    
                    self.logisticsNo = models.last?.list?.last?.traceNo
                    
                    self.items = models.map { PrescriptionOrderLogisticsSectionViewModel(with: $0) }
                }
                
                self.updateClosure?()
            }
        } failure: { error in
            HUDTool.hideActivity()
            HUDTool.showError(message: error?.description)
        }

    }
}
